var app = angular.module('app');

app.service('Storage', [function() {
    return {
        get: function(key) {
            var result = localStorage.getItem(key);
            try {
                result = JSON.parse(result);
            } catch (e) {}
            return result;
        },
        set: function(key, value) {
            if (typeof(value) != 'String') {
                value = JSON.stringify(value);
            }
            return localStorage.setItem(key, value);
        },
    };
}]);

app.service('FileSystem', ['Nw', function(Nw) {
    var fileprefix = 'file@';
    var dirprefix = 'dir@';

    var fs = {
        read: function(path) {
            return Nw.FileSystem.read(path);
        },
        //写入文件
        write: function(path, content) {
            return Nw.FileSystem.write(path, content);
        },
        //获取文件列表
        files: function(dir) {
            return Nw.FileSystem.files(dir);
        },
        //创建新的文件
        create: function(dir, filename) {
            return Nw.FileSystem.create(dir, filename);
        },
    };
    return fs;
}]);

app.service('log', function() {
    return {
        info: function(message) {
            alert(JSON.stringify(message));
            console.log(message);
        },
        debug: function(message) {
            alert(JSON.stringify(message));
            console.log(message);
        },
        error: function(message) {
            alert(JSON.stringify(message));
            console.log(message);
        }
    };
});

app.service('Qiniu', ['$http', function($http) {
    var host = 'http://up.qiniu.com',
        domain = 'http://ocib15b5s.bkt.clouddn.com',
        key = 'testkey.md', //文件名称
        token = '-To0_H7GdHGgSck21lxzpXUQ-DPVFvWSkg00T99O:rC-eyFusEwVLzPBQG4Mz8YW21q4=:eyJpbnNlcnRPbmx5IjowLCJzY29wZSI6Imxlc3NtZCIsImRlYWRsaW5lIjoxNDcyNTUyNDM4fQ==', //token
        // crc32 = '',
        // accept = '',
        filename = 'test.md';

    var boundary = "---------------------------7da24f2e50046";
    var body = '--' + boundary + '\r\nContent-Disposition:form-data; name="token"\r\n\r\n' + token + '\r\n--' + boundary + '\r\nContent-Disposition:form-data; name="key"\r\n\r\n@key\r\n--' + boundary + '\r\nContent-Disposition: form-data; name="file";filename="@filename"\r\nContent-type: plain/text\r\n\r\n@content\r\n--' + boundary + '--';
    var contentType = 'multipart/form-data; boundary=' + boundary;

    var qn = {
        write: function(dir, filename, content) {
            return $http({
                method: 'POST',
                url: host,
                headers: {
                    'Content-Type': contentType
                },
                data: body.replace('@key', dir + '/' + filename).replace('@filename', filename).replace('@content', content)
            });
        },
        read: function(dir, filename) {
            return $http.get(domain + '/' + dir + '/' + filename);
        }
    };

    return qn;
}]);

app.service('Nw', ['$q', 'log', function($q, log) {
    var self = {};

    function FileSystem() {
        var fs = nw.require('fs');
        return {
            read: function(path) {
                return fs.readFileSync(path, "utf-8");;
            },
            write: function(path, content) {
                var defer = $q.defer();
                return fs.writeFileSync(path, content);
            },
            files: function(path) {
                return fs.readdirSync(path);
            }
        };
    }

    function Path() {
        var path = nw.require('path');
        return path;
    }

    function Window() {
        var win = require('nw.gui').Window.get();
        return {
            enterFullscreen: function() {
                win.enterFullscreen();
            },
            leaveFullscreen: function() {
                win.leaveFullscreen();
            },
        }
    }
    self.FileSystem = new FileSystem();
    self.Path = new Path();
    self.Window = new Window();
    return self;
}]);

app.service('Folder', ['Storage', function(Storage) {
    var fkey = 'folders';
    var ckey = 'currnet_folder_index';

    var self = {
        list: function() {
            return Storage.get(fkey);
        },
        add: function(folder) {
            var list = self.list();

            list ? list.push(folder) : list = [folder];

            Storage.set(fkey, list);

            return list
        },
        del: function(index) {
            var list = self.list();
            list.splice(index, 1);
            Storage.set(fkey, list);

            return list;
        },
        current: function(index) {
            if (index != undefined) {
                Storage.set(ckey, index);
                return index;
            }
            return Storage.get(ckey);
        }
    };
    return self;
}]);
